<template>
	<view>
		<map id="myMap" style="width: 100%; height: 300px;" :longitude="startLng" :latitude="startLat" scale='16'
			:polyline="polyline" :markers="markers" show-location>
		</map>

		<!-- 司机信息卡片 -->
		<view class="driver-card">
			<view class="driver-header">
				<text class="card-title">司机已接单</text>
				<text class="eta">预计{{estimatedTime}}分钟到达</text>
			</view>

			<view class="driver-info">
				<image class="driver-avatar" :src="driverInfo.avatar" mode="aspectFill"></image>
				<view class="driver-details">
					<view class="driver-name">{{driverInfo.name}}</view>
					<view class="car-info">{{phone}}</view>
					<view class="driver-rating">
						<text class="rating-score">{{driverInfo.rating}}分</text>
					</view>
				</view>
			</view>

			<view class="action-buttons">
				<van-button custom-class="action-btn" icon="chat-o" plain type="primary" size="small"
					@click="sendMessage">短信联系</van-button>
				<van-button custom-class="action-btn" icon="contact-o" plain type="primary" size="small"
					@click="ContactDriver">联系司机</van-button>
				<van-button custom-class="action-btn" icon="close" plain type="default" size="small"
					@click="cancelOrder">取消订单</van-button>
			</view>
			<view class="confirm-ride-container">
				  <van-button 
					custom-class="confirm-ride-btn"
					@click="pickup"
				  >
					确认上车
				  </van-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		callWithErrorHandling
	} from 'vue';
	import selectCarApi from '@/api/selectCar.js';
	import QQMapWX from '../../common/qqmap-wx-jssdk.js';
	export default {
		data() {
			return {
				startLat: null,
				startLng: null,
				endLat: null,
				endLng: null,
				distanceLat: null,
				distanceLng: null,
				qqmapsdk: '',
				polyline: [],
				markers: [],
				currentLocation: '',
				watchId: null,
				isArrived: false,
				// 添加司机信息
				estimatedTime: 5,
				orderId: null,
				driverInfo: {
					driverId: "",
					name: '',
					avatar: '',
					carNumber: '',
					rating: null,
					orderCount: null,
					phone: ''
				},
				phone:null
			}
		},
		methods: {
			//进行经纬度转换为距离的计算
			Rad(d) {
				return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
			},
			/*
			 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
			 默认单位km
			*/
			getMapDistance(lat1, lng1, lat2, lng2) {
				// console.log("in getMap")
				// console.log(lat1)
				var radLat1 = this.Rad(lat1);
				var radLat2 = this.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = this.Rad(lng1) - this.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS-地球半径;
				s = Math.round(s * 10000) / 10000; //输出为公里
				s = s.toFixed(1);
				//s=s.toFixed(2);
				console.log(s,11111111111111111111111111111);
				return s;
			},
			// 检查是否到达目的地
			checkArrival() {
				const distance = this.getMapDistance(
					this.startLat,
					this.startLng,
					this.endLat,
					this.endLng
				);
				this.estimatedTime = distance * 2;
				console.log("时间: " + this.estimatedTime);
				// 如果距离小于50米，认为到达目的地
				if (distance < 0.1 && !this.isArrived) {
					this.isArrived = true;
					uni.showToast({
						title: '司机已到达',
						icon: 'success',
						duration: 2000
					});
					// 停止位置更新
					uni.stopLocationUpdate();
					uni.offLocationChange();
				}
			},
			//联系司机跳转到聊天界面
			ContactDriver() {
				uni.navigateTo({
					url: `/pages/contactDrivers/contactDrivers?driverId=${this.driverInfo.driverId}`
				});
			},
			// 开始监听位置变化
			startLocationWatch() {
				uni.startLocationUpdate({
					success: () => {
						console.log('开始监听位置变化');
					},
					fail: (err) => {
						console.error('监听位置失败：', err);
					}
				});

				// 监听位置变化事件
				uni.onLocationChange((res) => {
					// 更新起点位置
					this.startLat = res.latitude;
					this.startLng = res.longitude;
					//发送位置给司机
					this.sendMessages();
					// 更新起点标记
					this.updateStartMarker();
					// 检查是否到达目的地
					this.checkArrival();
					// 如果还没到达目的地，继续规划路线
					if (!this.isArrived) {
						this.planRoute();
					}
				});
			},

			// 更新起点标记-随着用户的移动而移动
			updateStartMarker() {
				const startMarker = {
					id: 0,
					latitude: this.startLat,
					longitude: this.startLng,
					iconPath: '../../static/destination.png',
					width: 40,
					height: 40,
					callout: {
						content: '当前位置',
						color: '#000000',
						fontSize: 14,
						borderRadius: 4,
						padding: 5,
						display: 'ALWAYS'
					}
				};
				// 更新markers数组中的起点标记
				if (this.markers.length > 0) {
					this.markers[0] = startMarker;
					// this.markers[1] = driverMarker;
				} else {
					this.markers.push(startMarker);
					// this.markers.push(driverMarker);
				}
			},

			planRoute() {
				//使用定位api
				this.qqmapsdk = new QQMapWX({
					key: '2HDBZ-B726C-TJS2Y-ARHHM-YXOAO-3NF4C'
				});

				//启用路线规划
				this.qqmapsdk.direction({
					mode: 'driving',
					from: `${this.startLat},${this.startLng}`,
					to: `${this.endLat},${this.endLng}`,
					success: (res) => {
						// console.log('路线规划结果：', res);
						const ret = res;
						const coors = ret.result.routes[0].polyline;
						const pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						const kr = 1000000;
						for (let i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						}
						//将解压后的坐标放入点串数组pl中
						for (let i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							});
						}
						// console.log('路线坐标点：', pl);

						// 更新路线数据
						this.polyline = [{
							points: pl,
							color: '#009a00dd',
							width: 10
						}];

						// 设置终点标记为接收到的目的地地址
						if (this.markers.length < 2) {
							const endMarker = {
								id: 1,
								latitude: this.endLat,
								longitude: this.endLng,
								iconPath: '/static/car.png',
								width: 50,
								height: 50,
								callout: {
									content: '司机位置',
									color: '#000000',
									fontSize: 14,
									borderRadius: 4,
									padding: 5,
									display: 'ALWAYS'
								}
							};
							this.markers.push(endMarker);
						}
					},
					fail: (error) => {
						console.error('路线规划失败：', error);
						
					},
					complete: (res) => {
						uni.showToast({
							title: '路线规划完成',
							icon: 'none'
						});
						// console.log('路线规划完成：', res);
						// console.log(res.result.routes[0].steps);
					}
				});
			},
			//获取接收到的目的地定位地址解析后的地址
			getAddress(lat, long) {
				// console.log(lat, long, 23232);
				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: lat,
						longitude: long
					},
					success: (res) => {
						// console.log('Reverse geocoding result:', res);
						let {
							address,
							ad_info
						} = res.result;
						this.address = ad_info.city ? ad_info.city : '定位失败';
						this.currentLocation = res.result.address;
						// console.log('Address:', this.address);
					},
					fail: (err) => {
						console.error('Reverse geocoding failed:', err);
					}
				});
			},
			// 添加联系司机方法
			contactDriver() {
				uni.makePhoneCall({
					phoneNumber: this.driverInfo.phone,
					success: (res) => {
						console.log('拨打电话成功');
					},
					fail: (err) => {
						console.error('拨打电话失败：', err);
					}
				});
			},

			// 添加短信联系方法
			sendMessage() {
				uni.sendSms({
					phoneNumber: this.driverInfo.phone,
					success: (res) => {
						console.log('发送短信成功');
					},
					fail: (err) => {
						console.error('发送短信失败：', err);
					}
				});
			},

			// 添加取消订单方法
			cancelOrder() {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消订单吗？',
					success: (res) => {
						if (res.confirm) {
							// 这里添加取消订单的逻辑
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							});
							// 返回上一页
							uni.navigateBack();
						}
					}
				});
			},
			//确认上车按钮
			pickup(){
				uni.navigateTo({
					url: `/pages/goDistance/goDistance?startLat=${this.startLat}&startLng=${this.startLng}&endLat=${this.distanceLat}&endLng=${this.distanceLng}&orderId=${this.orderId}`
				});
			},
			//发送当前位置
			sendMessages() {
				//重新计算坐标
				const x = this.startLat * 1000000;
				const y = this.startLng * 1000000;
				//发送消息
				if (this.socket) {
					const message = {
						id: this.driverInfo.driverId,
						style: "driver",
						x: x,
						y: y
					};
					this.socket.send({
						data: JSON.stringify(message),
						success: () => {
							console.log('消息发送成功');
						},
						fail: (err) => {
							console.error('消息发送失败:', err);
						}
					});
				} else {
					console.error('WebSocket连接未建立');
				}
			},
			//查询司机
			async getDriver() {
			      try {
			        const res = await selectCarApi.getDrivers(this.orderId);
			        this.phone = this.maskPhoneNumber(res.phone);
			        console.log('查询司机', res);
			        this.driverInfo = {
			            driverId: res.driverId,
			            name: res.name,
			            avatar: res.avatar,
			            rating: res.rating,
						phone: res.phone
			          };
					// 接收终点坐标
					this.endLat = res.driverX / 1_000_000.0;
					this.endLng = res.driverY / 1_000_000.0;
			        console.log(this.driverInfo, '司机信息');
			      } catch (err) {
			        console.error('查询司机失败:', err);
			      }
			    },
			//隐藏手机号部分
			maskPhoneNumber(phone) {
				if (phone.length !== 11) return "无效手机号"; // 确保手机号是11位
				return phone.substring(0, 2) + "*******" + phone.substring(9, 11);
			},
		},
		onLoad(e) {
			// 接收起点坐标
			this.startLat = parseFloat(e.startLat);
			this.startLng = parseFloat(e.startLng);
			this.distanceLat = parseFloat(e.endLat);
			this.distanceLng = parseFloat(e.endLng);
			//接收订单$
			this.orderId = e.orderId;
			console.log('订单',this.orderId);
			
			// console.log('起点坐标：', this.startLat, this.startLng);
			// console.log('终点坐标：', this.endLat, this.endLng);
			//根基单号查询司机
			this.getDriver()
			//获取乘客的token
			const token = uni.getStorageSync('token');

			this.socket = uni.connectSocket({
				url: 'ws://127.0.0.1:8005/realTime',
				header: {
					'Token': token, //redis中存放用户信息的key值
					'sender_type': 'passenger', //发送方类型
				},
				success: () => console.log('连接建立中...')
			});
			this.socket.onOpen(() => {
				console.log('WebSocket连接已打开');
			});

			let isPlanning = false;
			this.socket.onMessage(res => {
				// console.log('收到消息:', res.data);
				const msg = JSON.parse(res.data)

				// 更新终点坐标
				this.endLat = parseFloat(msg.x / 1000000);
				this.endLng = parseFloat(msg.y / 1000000);
				if (!isPlanning) {
					isPlanning = true;
					setTimeout(() => {
						this.planRoute();
						isPlanning = false;
					}, 1000); // 每秒最多调用一次
				}
				//this.scrollToBottom();
			});

			this.socket.onError(err => {
				console.error('WebSocket错误:', err);
			});

			this.socket.onClose(() => {
				console.log('WebSocket连接已关闭');
			});




			// 初始化地图后规划路线
			this.$nextTick(() => {
				this.planRoute();
				this.getAddress(this.endLat, this.endLng);
				// 开始监听位置变化
				this.startLocationWatch();
			});
		},
		// 组件销毁时停止监听
		onUnload() {
			if (this.watchId) {
				uni.stopLocationUpdate();
				uni.offLocationChange();
			}
		}
	}
</script>

<style>
	.driver-card {
		background-color: #FFFFFF;
		border-radius: 16px;
		margin: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	}

	.driver-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.eta {
		font-size: 28rpx;
		color: #666;
	}

	.driver-info {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.driver-avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		margin-right: 20rpx;
	}

	.driver-details {
		flex: 1;
	}

	.driver-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}

	.car-info {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.driver-rating {
		display: flex;
		align-items: center;
	}

	.rating-score {
		font-size: 28rpx;
		color: #FFA500;
		margin-right: 20rpx;
	}

	.order-count {
		font-size: 28rpx;
		color: #999;
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
	}

	/* 自定义vant按钮样式 */
	.action-btn {
		flex: 1;
		margin: 0 20rpx !important;
	}

	/* 去除第一个按钮的左边距 */
	.action-buttons .action-btn:first-child {
		margin-left: 0 !important;
	}

	/* 去除最后一个按钮的右边距 */
	.action-buttons .action-btn:last-child {
		margin-right: 0 !important;
	}
/* 确认上车按钮容器 */
.confirm-ride-container {
  width: 100%;
  margin-top: 15px;
}
 
/* 确认上车按钮样式 */
.confirm-ride-btn {
  width: 100%;
}
</style>